export const setProperty = (prop: string, val: any, dom = document.documentElement) => {
    dom.style.setProperty(prop, val);
};

export const mix = (color1: string, color2: string, weight: number = 0.5): string => {
    let color = '#';
    for (let i = 0; i <= 2; i++) {
        const c1 = parseInt(color1.substring(1 + i * 2, 3 + i * 2), 16);
        const c2 = parseInt(color2.substring(1 + i * 2, 3 + i * 2), 16);
        const c = Math.round(c1 * weight + c2 * (1 - weight));
        color += c.toString(16).padStart(2, '0');
    }
    return color;
};

/**
 * 将"yyyy-MM-dd HH:mm:ss"格式的字符串转换为Date对象
 * @param dateString 日期时间字符串，格式为"yyyy-MM-dd HH:mm:ss"
 * @returns Date对象
 */
export const parseDateTimeString = (dateString: string): Date => {
    // 使用正则表达式验证输入格式
    const regex = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/;
    if (!regex.test(dateString)) {
        throw new Error('Invalid date format. Expected format: yyyy-MM-dd HH:mm:ss');
    }

    // 将日期字符串转换为Date对象
    const date = new Date(dateString.replace(/-/g, '/').replace(' ', 'T'));
    
    // 检查日期是否有效
    if (isNaN(date.getTime())) {
        throw new Error('Invalid date value');
    }
    
    return date;
};

/**
 * 将Date对象转换为"yyyy-MM-ddTHH:mm:ss"格式的字符串
 * @param date Date对象
 * @returns 格式化后的日期时间字符串
 */
export const formatDateTime = (date: Date): string => {
    if (!(date instanceof Date)) {
        throw new Error('Input must be a Date object');
    }

    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');

    return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
};